package net.bat.cms;

import java.util.List;
import java.util.Map;

import net.bat.entity.Article;
import net.bat.entity.Attach;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CMSController {
	@Autowired
	private CMSService cmsService;
	public final static String TPL_DEFAULT = "default";
	public final static String PATH_ARTICLE = "/article/";
	public final static String URI_ARTICLE = "/article_uri/";

	@RequestMapping(value = URI_ARTICLE + "{id}", method = RequestMethod.GET)
	@ResponseBody
	public String[] getArticleURI(@PathVariable("id") long id) {
		return cmsService.getArticleURI(id);
		/*
		 * StringBuffer sbuf = new StringBuffer();
		 * for (String uri : uris) {
		 * if (sbuf.length() == 0) {
		 * sbuf.append(uri);
		 * } else {
		 * sbuf.append("\n" + CMSService.splitSec);
		 * }
		 * }
		 * return sbuf.toString();
		 */}

	@RequestMapping(value = PATH_ARTICLE + "{id_tpl}", method = RequestMethod.GET)
	public String showDetailByTpl(@PathVariable("id_tpl") String id_tpl, Model model) {
		try {
			String[] prs = id_tpl.split("_");
			long id = Long.parseLong(prs[0]);
			Article obj = cmsService.getArticle(id);
			// TODO 检查status 状态, 只允许管理员预览
			model.addAttribute("obj", obj);
			List<Attach> ls = cmsService.getArticleAttachs(id);
			if (ls != null) {
				model.addAttribute("robjs", ls.toArray());
			}
			String tpl;
			if (prs.length == 1) {
				tpl = TPL_DEFAULT;
			} else {
				tpl = prs[1];
			}
			// 根据频道绑定多个文章模版
			return "tpl" + PATH_ARTICLE + tpl;
		} catch (Exception e) {
			e.printStackTrace();
			return "error/404";
		}
	}

	@RequestMapping(value = "/list/Attach/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public <T> T updateAttach(@PathVariable Long id, @RequestBody Map<String, Object> rmap) throws Exception {
		return (T) cmsService.updateAttach(id, rmap);
	}

	@RequestMapping(value = "/rest/Article/{id}", method = RequestMethod.PUT)
	@ResponseBody
	public <T> T updateEntity(@PathVariable Long id, @RequestBody Map<String, Object> rmap) throws Exception {
		return (T) cmsService.updateArticle(id, rmap);
	}

	@RequestMapping(value = "/rest/Article", method = RequestMethod.POST)
	@ResponseBody
	public <T> T updateEntity(@RequestBody Map<String, Object> rmap) throws Exception {
		return (T) cmsService.updateArticle(rmap);
	}

}
